package com.scze.imdemo.myapplication.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.NetUtils;
import com.scze.imdemo.R;
import com.scze.imdemo.myapplication.ChatAgentEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * @author ：皮阳波
 * @date ：2017/4/27 9:49
 * @Description:
 */
public class ChatActivity extends AppCompatActivity {
    private Button fs;
    private EditText sr;
    private LinearLayout ll;
    //
    private String userName = "picontent";
    private String password = "picontent";
    private String toChatUsername = "kefuchannelimid_804756";
    private String content;
    private boolean RgState = false;      //人工状态
    private int code = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        init();
        //注册失败会抛出HyphenateException

        System.out.println("z:" + userName + "d:" + password);
        //登陆是否成功回调
        login();
        //自动登录属性默认是 true   options.setAutoLogin(false);
        //登出判断
        //loginOut();
        //注册网络连接状态监听
        networkListener();
        //接受聊天信息
        acceptChatNews();
        //发送信息按钮
        fs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
                EMMessage message = EMMessage.createTxtSendMessage(sr.getText().toString(), toChatUsername);
                //发送消息
                EMClient.getInstance().chatManager().sendMessage(message);
                showChatContent(EMClient.getInstance().getCurrentUser(),sr.getText().toString());
                sr.setText(null);
            }
        });
    }

     View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            RgState = true;
            //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
            EMMessage message = EMMessage.createTxtSendMessage("com.scze.zwt.code.1", toChatUsername);
            //发送消息
            EMClient.getInstance().chatManager().sendMessage(message);
            showToast("正在转人工服务。");
        }
    };

    //显示聊天的内容
    private void showChatContent(String name,String content){
        content = name + ":\r\n" + "              " +content;
        TextView textView = new Button(ChatActivity.this);
        textView.setText(content);
        textView.setGravity(Gravity.LEFT);
        ll.addView(textView);
        /////
        if(name.equals("正易机器人客服")){
            Button button = new Button(ChatActivity.this);
            button.setOnClickListener(onClickListener);
            button.setText("人工服务");
            button.setTextColor(Color.RED);
            ll.addView(button);
        }

    }

    private void acceptChatNews() {
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }
    private void showToast(final String content2){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ChatActivity.this,content2, LENGTH_SHORT).show();
            }
        });
    }
    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            showToast("收到消息");
            final EMMessage message = messages.get(messages.size()-1);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject j = message.getJSONObjectAttribute("weichat");
                        JSONObject j2 =  j.getJSONObject("agent");
                        ChatAgentEntity chatAgentEntity = new ChatAgentEntity();
                        chatAgentEntity.setAvatar(j2.getString("avatar"));
                        chatAgentEntity.setUserNickname(j2.getString("userNickname"));
                        JSONObject j3 = j.getJSONObject("html_safe_body");
                        String content = j3.getString("msg");
                        if(RgState){
                            RgState = false;
                            EMMessage message = EMMessage.createTxtSendMessage("1", toChatUsername);
                            //发送消息
                            EMClient.getInstance().chatManager().sendMessage(message);
                        }else{
                            showChatContent(chatAgentEntity.getUserNickname(),content);
                        }

//                        if(content.equals("com.scze.zwt.code.1")){
//                            EMMessage message = EMMessage.createTxtSendMessage("1", toChatUsername);
//                            //发送消息
//                            EMClient.getInstance().chatManager().sendMessage(message);
//                        }else{
//                            showChatContent(chatAgentEntity.getUserNickname(),content,1);
//                        }
//                            System.out.println("内容：" + content);
                            System.out.println(j.toString());
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
            showToast("收到透传消息");
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
            showToast("收到已读回执");
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
            showToast("收到已送达回执");
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
            showToast("消息状态变动" + message.getBody()  .toString());
        }
    };

    private void networkListener() {
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
    }

    private void login() {
        Log.d("登录聊天", "z:" + userName + "d:" + password);
        EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                        EMClient.getInstance().getCurrentUser();
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                System.out.println("登录聊天服务器失败!code:" + code+"|||" + message);
            }
        });
    }

    private void loginOut() {
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                System.out.println("out:" + 1);
            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub
                System.out.println("out:" + 2);
            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub
                System.out.println("out:" + 3+"onError");
            }
        });
    }


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }
        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                        System.out.println("显示帐号已经被移除");
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        System.out.println("显示帐号在其他设备登录");
                    } else {
                        if (NetUtils.hasNetwork(ChatActivity.this)){
                            //连接不到聊天服务器
                            System.out.println("显示连接不到聊天服务器"+ error);
                        } else{
                            //当前网络不可用，请检查网络设置
                            System.out.println("显示当前网络不可用，请检查网络设置");
                        }

                    }
                }
            });
        }
    }

    private void init() {
        fs = (Button) findViewById(R.id.fs);
        sr = (EditText) findViewById(R.id.sr);
        ll = (LinearLayout) findViewById(R.id.ll);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //记得在不需要的时候移除listener，如在activity的onDestroy()时
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        loginOut();
    }
}
